import { useState } from 'react';
import { Form, Input, Select, InputNumber, Upload, Button, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { addGoods, uploadGoodsImg } from '@/api/account';
import { serverUrl } from '@/utils/common';

const { Option } = Select;
const { TextArea } = Input;

const Add = () => {
  const [form] = Form.useForm();
  const [imageUrl, setImageUrl] = useState('');
  const [loading, setLoading] = useState(false);

  const onFinish = async (values) => {
    if (!imageUrl) {
      message.warning('请上传商品图片');
      return;
    }

    const submitData = {
      ...values,
      imgUrl: imageUrl
    };

    try {
      setLoading(true);
      const response = await addGoods(submitData);
      
      if (response.code === 0) {
        message.success(response.msg);
        form.resetFields();
        setImageUrl('');
      } else if (response.code === 1 || response.code === 5001) {
        message.error(response.msg);
      }
    } catch (error) {
      message.error('请求失败，请稍后再试');
      console.error('添加商品失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const beforeUpload = (file) => {
    const isImage = file.type.includes('image');
    if (!isImage) {
      message.error('商品头像必须是图片');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过2MB!');
      return false;
    }
    return true;
  };

  const handleUpload = async (options) => {
    const { file, onSuccess, onError } = options;
    const formData = new FormData();
    formData.append('file', file);

    try {
      const res = await uploadGoodsImg(formData);
      if (res.code === 0) {
        const fileName = res.imgUrl.split('/').pop();
        setImageUrl(fileName);
        onSuccess(res);
        message.success('图片上传成功');
      } else {
        onError();
        message.error(res.msg);
      }
    } catch (error) {
      onError();
      message.error('上传失败');
    }
  };

  const uploadButton = (
    <div>
      {imageUrl ? null : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  return (
    <div className="simple-add-product">
      <h3>添加商品</h3>
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        onFinish={onFinish}
      >
        {/* 商品名称 */}
        <Form.Item
          label="商品名称"
          name="name"
          rules={[{ required: true, message: '请输入商品名称' }]}
        >
          <Input placeholder="输入商品名称" />
        </Form.Item>
        
        {/* 商品分类 */}
        <Form.Item
          label="商品分类"
          name="category"
          rules={[{ required: true, message: '请选择分类' }]}
        >
          <Select placeholder="选择分类">
            <Option value="营养餐">营养餐</Option>
            <Option value="烧烤">烧烤</Option>
            <Option value="小吃">小吃</Option>
          </Select>
        </Form.Item>
        
        {/* 商品价格 */}
        <Form.Item
          label="商品价格"
          name="price"
          rules={[{ required: true, message: '请输入商品价格' }]}
        >
          <InputNumber min={0} style={{ width: '100%' }} />
        </Form.Item>
        
        {/* 商品图片 */}
        <Form.Item label="商品图片">
          <Upload
            name="avatar"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            beforeUpload={beforeUpload}
            customRequest={handleUpload}
          >
            {imageUrl ? (
              <img
                src={`${serverUrl}/upload/imgs/goods_img/${imageUrl}`}
                alt="商品图片"
                style={{ width: '100%' }}
              />
            ) : (
              uploadButton
            )}
          </Upload>
        </Form.Item>
        
        {/* 商品描述 */}
        <Form.Item
          label="商品描述"
          name="goodsDesc"
          rules={[{ required: true, message: '请输入商品描述' }]}
        >
          <TextArea rows={3} placeholder="输入商品描述" />
        </Form.Item>
        
        {/* 添加按钮 */}
        <Form.Item wrapperCol={{ offset: 4, span: 18 }}>
          <Button type="primary" htmlType="submit" loading={loading}>
            添加商品
          </Button>
        </Form.Item>
      </Form>

      <style jsx>{`
        .simple-add-product {
          max-width: 600px;
          margin: 20px auto;
          padding: 20px;
        }
        .avatar-uploader {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          width: 100px;
          height: 100px;
        }
        .avatar-uploader:hover {
          border-color: #1890ff;
        }
      `}</style>
    </div>
  );
};

export default Add;